/*
 * @Author: 肖思汗 
 * @Date: 2025-06-16 11:48:14 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-25 17:59:43
 */


import Taro from "@tarojs/taro";
import { makeAutoObservable, toJS } from "mobx";
import shoppingCartStore from "src/pages/ShoppingCart/shoppingCartStore";
import designerStore from "../Designer/designerStore";
import perview3der from "./PreView2D3D/perview3der";
import utilsApi from "src/api/utilsApi";
import utils from "src/utils/utils";
import Api from "src/api/Api";
import { GoodsData } from "types/type";
import { get } from "lodash";
import goOnPreDesignStore from "src/pages/Index/GoOnPreDesign/goOnPreDesignStore";

class RightTopStore {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });
    }

    saveing = false;
    setSaveing(value: boolean) {
        this.saveing = value;
    }


    // 保存设计数据
    save = async () => {
        this.setSaveing(true);
        const fontThumbFile = await perview3der.getFrontThumb();
        const backThumbFile = await perview3der.getBackThumb();
        const fontThumbUrl = fontThumbFile ? await utilsApi.uploadOss(fontThumbFile, Api.ossDirectory) : fontThumbFile;
        const backThumbUrl = backThumbFile ? await utilsApi.uploadOss(backThumbFile, Api.ossDirectory) : backThumbFile;

        const productId = Taro.getStorageSync('designer_productId'); //商品id
        const size = Taro.getStorageSync('designer_size'); // 规格
        const { goodsBaseData, selectColor } = designerStore;

        // 设计数据
        const productDesign: GoodsData["productData"] = {
            ...toJS(designerStore.designData),
            thumbs: [fontThumbUrl, backThumbUrl], // 商品图片数组
        };

        const hasFront = (get(productDesign.designData, ['front', 'objects', 'length']) || 0) > 0;
        const hasBack = (get(productDesign.designData, ['back', 'objects', 'length']) || 0) > 0;

        if (hasFront && hasBack) {
            productDesign.printArea = 'double';
        } else if (!hasFront && hasBack) {
            productDesign.printArea = 'back';
        } else {
            productDesign.printArea = 'front';
        }

        await shoppingCartStore.add({
            productId: productId, // 商品id
            productNegativeId: goodsBaseData.productNegativeId, // 底板id
            designName: designerStore.designData.designName, // 设计者名称
            productDesign: productDesign, // 设计数据
            productShowImageUrl: fontThumbUrl, // 商品图片
            size: size, // 规格
            color: selectColor, // 颜色
            addToDesign: true
        });
        Taro.switchTab({
            url: '/pages/ShoppingCart/ShoppingCart',
            success: () => {
                goOnPreDesignStore.setTemp_designer(undefined);
            }
        });
        this.setSaveing(false);
    };

}

const rightTopStore = new RightTopStore();

export default rightTopStore;
